import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, message, Table} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE, TABLE} from '../constants';
import {conventEnumValueToString, formatAmount} from '../utils';
import WrappedSelect from '../common/WrappedSelect';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {validateAdd} from './utils';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import {packingType, transportType, currency} from '../Enum';
const FormItem = Form.Item;
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];

const rowKey = record => `${record.partSaleOrderCode}${record.partCode}`;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        isForwarderSearch: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    onSubmit = () => {
        const result = validateAdd(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    render() {
        const {details = []} = this.props.conditions;
        let totalQuantity = 0;
        details.forEach(o => {
            totalQuantity += (o.quantity);
        });
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partSaleOrderCode',
                    defaultMessage: '销售订单编号'
                }),
                dataIndex: 'partSaleOrderCode',
                render: (text, record) => {
                    const obj = {
                        children: text,
                        props: {},
                    };
                    obj.props.rowSpan = record.rowSpan;
                    return obj;
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName',
                render: (text, record) => {
                    const obj = {
                        children: text,
                        props: {},
                    };
                    obj.props.rowSpan = record.rowSpan;
                    return obj;
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: (text, record) => {
                    const obj = {
                        children: conventEnumValueToString(currency, text),
                        props: {},
                    };
                    obj.props.rowSpan = record.rowSpan;
                    return obj;
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: (text, record) => {
                    const obj = {
                        children: conventEnumValueToString(transportType, text),
                        props: {},
                    };
                    obj.props.rowSpan = record.rowSpan;
                    return obj;
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.pickingListCode',
                    defaultMessage: '备件备料单号'
                }),
                dataIndex: 'pickingListCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.palletCode',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.oldPartCode',
                    defaultMessage: '被替换备件编号'
                }),
                dataIndex: 'oldPartCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.oldPartName',
                    defaultMessage: '被替换备件名称'
                }),
                dataIndex: 'oldPartName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.totalAmount',
                    defaultMessage: '总价'
                }),
                dataIndex: 'totalAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '装箱单信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '箱单号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.conditions.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.packingType ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.packingType',
                                            defaultMessage: '包装类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            name="packingType"
                                            value={this.props.conditions.packingType}
                                            options={packingType.toList(language)}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.container',
                                            defaultMessage: '包装规格'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.container}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.length ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.length',
                                            defaultMessage: '长度'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            name="length"
                                            value={this.props.conditions.length}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.width ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.width',
                                            defaultMessage: '宽度'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            name="width"
                                            value={this.props.conditions.width}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.height ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.height',
                                            defaultMessage: '高度'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            name="height"
                                            value={this.props.conditions.height}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.volume ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.volume',
                                            defaultMessage: '体积'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            pagination={3}
                                            name="volume"
                                            value={this.props.conditions.volume}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.netWeight ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.netWeight',
                                            defaultMessage: '净重'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            pagination={3}
                                            name="netWeight"
                                            value={this.props.conditions.netWeight}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.grossWeight ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.grossWeight',
                                            defaultMessage: '毛重'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            min={0}
                                            precision={3}
                                            name="grossWeight"
                                            value={this.props.conditions.grossWeight}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="remark" autosize={autosize}
                                        value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.details.title',
                                defaultMessage: '装箱单清单'
                            })}
                            bordered={false}>
                            <Table className="white-space-nowrap" rowKey={rowKey} columns={columns} pagination={false} dataSource={details} {...TABLE} />
                            {this.props.intl.formatMessage({
                                id: 'add.text.total',
                                defaultMessage: '总数量:'
                            })}{totalQuantity}
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickUpdate,
    getDetail,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: status =>
        dispatch(onClickUpdate(ownProps.id, status)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
